package com.maycari.captainbi.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.maycari.captainbi.common.constant.CommonConstant;
import com.maycari.captainbi.common.exception.BusinessException;
import com.maycari.captainbi.data.dto.AuthorizationManagementDto;
import com.maycari.captainbi.data.dto.SyncRecordDto;
import com.maycari.captainbi.service.AuthorizationManagementService;
import com.maycari.captainbi.service.SyncRecordService;
import com.maycari.captainbi.util.CaptainBIUtil;
import com.maycari.tool.utils.SpringUtil;
import com.maycari.tool.utils.StringUtil;
import com.maycari.tool.utils.ThreadUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @Author: 王宏伟
 * @DateTime: 2021/4/12 11:09
 * @Description: TODO
 */
@Component
@Slf4j
public class SyncListener {

    public static final String SYNC_LISTENER = "SYNC_LISTENER466612";

    @Autowired
    private AuthorizationManagementService authorizationManagementService;

    @Autowired
    private SyncRecordService syncRecordService;

    @JmsListener(destination = SYNC_LISTENER)
    public void receiveMessage(SyncDto dto) {
        log.info("SYNC_LISTENER Start 》》》》》>>>>>>>>>>>>>>>>>>>>>>");
        log.info("dto:--------------------- "+dto.toString());
        Integer authorizationId = dto.getAuthorizationId();
        AuthorizationManagementDto authorizationManagementDto = authorizationManagementService.selectById(authorizationId);
        if (authorizationManagementDto == null) {
            throw new BusinessException("授权信息不存在：" + authorizationId);
        }
        String syncRecordId;

        if (StringUtil.isNotBlank(dto.getSyncRecordId())) {

            syncRecordId = dto.getSyncRecordId();
        } else {
            syncRecordId = getUUID();
        }

        SyncRecordDto syncRecordDto = new SyncRecordDto();
        syncRecordDto.setAuthorizationId(authorizationId);
        syncRecordDto.setUrl(dto.getUrl());
        syncRecordDto.setParams(JSON.toJSONString(dto));
        syncRecordDto.setStatus(CommonConstant.SHIFOU.SHI.value());

        String key = authorizationManagementDto.getAppKey();
        String secret = authorizationManagementDto.getAppSecret();
        try {
            // 只包含发送的消息
            Object bean = SpringUtil.getBean(dto.getBeanId());
            JSONArray jsonArray = new JSONArray();
            if (dto.isNeedPage()) {
                int page = 1;
                int page_size = 100;
                while (true) {
                    TreeMap<String, String> params = dto.getParams();
                    params.put("page", String.valueOf(page));
                    params.put("page_size", String.valueOf(page_size));
                    String result = getData(dto.getUrl(), params, key, secret);
                    JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                    if (jsonObject.getIntValue("code") == 200) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        if (data != null && data.size() > 0) {
                            if (data.size() >= 100) {
                                //可能还有数据  继续请求
                                jsonArray.addAll(data);
                                page++;
                            } else {
                                jsonArray.addAll(data);
                                break;
                            }
                        } else {
                            break;
                        }
                    } else {
                        //失败时候的处理
                        throw new BusinessException(jsonObject.getString("msg"));
                    }
                }

            } else {
                TreeMap<String, String> params = dto.getParams();
                String result = getData(dto.getUrl(), params, key, secret);
                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                if (jsonObject.getIntValue("code") == 200) {
                    jsonArray = jsonObject.getJSONArray("data");
                } else {
                    throw new BusinessException(jsonObject.getString("msg"));
                }
            }
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONArray result = new JSONArray();
                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    jsonObject.put("authorizationId", authorizationId);
                    result.add(jsonObject);
                }
                Method me = bean.getClass().getDeclaredMethod("insertBatch", JSONArray.class);
                me.invoke(bean, result);
            }

        } catch (Exception e) {
            log.error("同步发生异常", e);
            syncRecordDto.setStatus(CommonConstant.SHIFOU.FOU.value());

            syncRecordDto.setSyncCount(0);

            syncRecordDto.setMsg(e.getMessage());
        }

        syncRecordDto.setId(syncRecordId);
        syncRecordService.insert(syncRecordDto);
    }

    private String getData(String url, TreeMap params, String key, String secret) {
        ThreadUtil.sleep(1000);
        log.info("请求船长BI接口》》》》");
        return CaptainBIUtil.sendRequest(url, params, key, secret);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
